const Storage = require('./storage').default
const STORAGE_TOKEN_NAME = 'auth_store_tokens'
const OPENID_STORAGE_KEY = 'auth_open_id'

let config  = require('../../static/config')
let engine = new Storage(wx);

const wxp = require('../../static/wx.promise').default

export function checkNetError(fun) {
  return new Promise(function(resolve, reject) {
    wx.getNetworkType({
      success: function(res) {
        let networkType = res.networkType
        if (networkType === 'none') {
          wx.showToast({
            title: '网络连接异常',
            icon: 'none',
            duration: 2000
          })
          resolve()
        } else {
          fun()
        }
      },
      fail(e) {
        fun()
      }
    })
  })
}

export async function wxLogin() {
  let wxLoginInfo = await wxp.login()
  console.d('wxLoginInfo', wxLoginInfo)
  if (wxLoginInfo.errMsg && wxLoginInfo.errMsg.indexOf('ok') > -1) {
    return wxLoginInfo
  } else {
    throw new Error('wx login failed')
  }
}

export function setOpenid(v) {
  wx.setStorageSync(OPENID_STORAGE_KEY, v)
}

export function getOpenid() {
  return wx.getStorageSync(OPENID_STORAGE_KEY)
}

export async function getOpenidByWxLoginCode(wxLoginCode, extraData) {
  let openid = getOpenid()
  return new Promise((resolve, reject) => {
    if (openid) {
      resolve(openid)
    } else {
      wx.request({
        url: config.authApi,
        method: 'POST',
        data: {
          code: wxLoginCode,
        },
        header: {
          'auth-sys': 'query',
        },
        success(res) {
          if (res.data.code > 20000) {
            reject(new Error('server return err ' + res.data.code))
          } else {
            if (!res.data.data) {
              reject(new Error('server return null'))
            }
            let openid = res
            setOpenid(openid)
            resolve(openid)
          }
        },
        fail(e) {
          let err = [
            'NETWORKERR_WHEN_LOGIN',
            new Error('network err')
          ]
          console.error.apply(console, err)
          checkNetError(() => {
          })
          reject(err[1])
        }
      })
    }
  })
}

export function setToken(d) {
  engine.set(STORAGE_TOKEN_NAME, d)
}

export function getToken() {
  return engine.get(STORAGE_TOKEN_NAME)
}
